/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package control;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import model.Drawer;
import model.Item;

/**
 *
 * @author Jonas
 */
public class ItemHandler {

    private DBLogin db;
    private ResultSet rs;
    private ArrayList<Drawer> drawerList;

    public ItemHandler(DBLogin db) {
        this.db = db;
    }

    public Drawer getDrawer(int i) {
        Drawer dw = null;
        for (Drawer drawer : drawerList) {
            if (drawer.getContainerID() == i) {
                dw = drawer;
            }
        }
        return dw;
    }

    public ArrayList getDrawerList() {
        return drawerList;
    }

    public void getItems() {
        String sql = "select * from cont_item join container on fk_cont_id = cont_id right outer join item on fk_item_id = item_id order by cont_id";
        try {
            rs = db.getStmt().executeQuery(sql);
            int currentDrawer = 0;
            ArrayList<Item> itemList = new ArrayList<>();
            drawerList = new ArrayList<>();

            while (rs.next()) {
                if (currentDrawer != rs.getInt("cont_id")) {
                    itemList = new ArrayList<>();
                    Drawer drawer = new Drawer(rs.getInt("cont_id"), itemList);
                    drawerList.add(drawer);
                }
                Item item = new Item(rs.getInt("item_id"), rs.getString("item_name"), rs.getString("item_unit"), rs.getInt("item_stock"));
                itemList.add(item);
                currentDrawer = rs.getInt("cont_id");
            }
        } catch (SQLException ex) {
            Logger.getLogger(ItemHandler.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void updateItemStock(Item it) throws SQLException {
        String sql = "UPDATE item SET item_stock = " + it.getItemStock() + " where item_id = " + it.getItemID();
        db.getStmt().execute(sql);
    }
}
